/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.api.runtime.process.impl;

import com.je.bpm.api.runtime.shared.model.impl.ListConverter;
import com.je.bpm.api.runtime.shared.model.impl.ModelConverter;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.engine.RepositoryService;
import com.je.bpm.model.process.model.ProcessDefinition;
import com.je.bpm.model.process.model.impl.ProcessDefinitionImpl;

import java.util.Map;
import java.util.Objects;

/**
 * 引擎持久化流程定义对象到API流程定义对象的转换器
 */
public class APIProcessDefinitionConverter extends ListConverter<com.je.bpm.engine.repository.ProcessDefinition, Map<String, Object>, ProcessDefinition>
        implements ModelConverter<com.je.bpm.engine.repository.ProcessDefinition,Map<String, Object>, ProcessDefinition> {

    private RepositoryService repositoryService;

    public APIProcessDefinitionConverter(RepositoryService repositoryService) {
        this.repositoryService = repositoryService;
    }

    @Override
    public ProcessDefinition from(com.je.bpm.engine.repository.ProcessDefinition internalProcessDefinition) {
        ProcessDefinitionImpl processDefinition = new ProcessDefinitionImpl();
        processDefinition.setId(internalProcessDefinition.getId());
        processDefinition.setName(internalProcessDefinition.getName());
        processDefinition.setDescription(internalProcessDefinition.getDescription());
        processDefinition.setVersion(internalProcessDefinition.getVersion());
        processDefinition.setKey(internalProcessDefinition.getKey());
        processDefinition.setAppVersion(Objects.toString(internalProcessDefinition.getAppVersion(), null));
        BpmnModel model = repositoryService.getBpmnModel(internalProcessDefinition.getId());
        processDefinition.setFormKey(model.getStartFormKey(internalProcessDefinition.getKey()));
        return processDefinition;
    }
}
